import 'package:craze/common/index.dart';
import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';
import '../models/user_model.dart';

class UserService {
  final Box<UserModel> _userBox = Hive.box<UserModel>('users');

  // 创建新用户
  Future<UserModel> createUser({
    required String username,
    required String password,
    required String name,
    required String email,
    String avatar = MyImages.touxiang1,
    String description = '',
  }) async {
    final uuid = Uuid();
    final user = UserModel(
      id: uuid.v4(),
      username: username,
      password: password,
      name: name,
      email: email,
      avatar: avatar,
      description: description,
    );

    await _userBox.put(user.id, user);
    return user;
  }

  // 通过ID获取用户
  UserModel? getUserById(String id) {
    return _userBox.get(id);
  }

  // 通过用户名获取用户
  UserModel? getUserByUsername(String username) {
    try {
      return _userBox.values.firstWhere((user) => user.username == username);
    } catch (e) {
      return null;
    }
  }

  // 更新用户信息
  Future<void> updateUser(UserModel user) async {
    await _userBox.put(user.id, user);
  }

  // 删除用户
  Future<void> deleteUser(String id) async {
    await _userBox.delete(id);
  }

  // 获取所有用户
  List<UserModel> getAllUsers() {
    return _userBox.values.toList();
  }

  // 关注用户
  Future<void> followUser(String currentUserId, String targetUserId) async {
    final currentUser = getUserById(currentUserId);
    final targetUser = getUserById(targetUserId);

    if (currentUser != null && targetUser != null) {
      currentUser.followingIds.add(targetUserId);
      targetUser.followerIds.add(currentUserId);

      await updateUser(currentUser);
      await updateUser(targetUser);
    }
  }

  // 取消关注用户
  Future<void> unfollowUser(String currentUserId, String targetUserId) async {
    final currentUser = getUserById(currentUserId);
    final targetUser = getUserById(targetUserId);

    if (currentUser != null && targetUser != null) {
      currentUser.followingIds.remove(targetUserId);
      targetUser.followerIds.remove(currentUserId);

      await updateUser(currentUser);
      await updateUser(targetUser);
    }
  }

  // 验证登录
  UserModel? authenticate(String username, String password) {
    try {
      return _userBox.values.firstWhere(
        (user) => user.username == username && user.password == password,
      );
    } catch (e) {
      return null;
    }
  }

  // 添加默认用户数据（开发测试用）
  Future<void> createSampleUsers() async {
    if (_userBox.isEmpty) {
      final sampleUsers = [
        {
          'username': 'lalala',
          'name': 'Ezra',
          'email': 'ezra@example.com',
          'avatar': 'assets/images/touxiang1.png',
          'description':
              'Passionate diver exploring coral reefs around the world. Love marine life and underwater photography.',
        },
        {
          'username': 'ocean',
          'name': 'Thea',
          'email': 'thea@example.com',
          'avatar': 'assets/images/touxiang2.png',
          'description':
              'Marine biologist specialized in tropical fish species. Working on coral reef conservation projects.',
        },
        {
          'username': 'coral',
          'name': 'Knox',
          'email': 'knox@example.com',
          'avatar': 'assets/images/touxiang3.png',
          'description':
              'Professional underwater photographer with 10+ years of diving experience. Ocean advocate.',
        },
        {
          'username': 'blue',
          'name': 'Wren',
          'email': 'wren@example.com',
          'avatar': 'assets/images/touxiang4.png',
          'description':
              'Dive instructor and marine conservation volunteer. Passionate about protecting sea turtles.',
        },
        {
          'username': 'shark',
          'name': 'Zeke',
          'email': 'zeke@example.com',
          'avatar': 'assets/images/touxiang5.png',
          'description':
              'Shark researcher and advocate for endangered marine species. Certified rescue diver.',
        },
        {
          'username': 'wave',
          'name': 'Maeve',
          'email': 'maeve@example.com',
          'avatar': 'assets/images/touxiang6.png',
          'description':
              'Ocean engineer working on sustainable solutions for coastal communities. Weekend diver.',
        },
        {
          'username': 'reef',
          'name': 'Pike',
          'email': 'pike@example.com',
          'avatar': 'assets/images/touxiang7.png',
          'description':
              'Coral reef restoration specialist with focus on climate change impact. Diving since childhood.',
        },
        {
          'username': 'fish',
          'name': 'Faye',
          'email': 'faye@example.com',
          'avatar': 'assets/images/touxiang8.png',
          'description':
              'Marine life artist and diving enthusiast. Documenting the beauty of underwater ecosystems.',
        },
        {
          'username': 'deep',
          'name': 'Jett',
          'email': 'jett@example.com',
          'avatar': 'assets/images/touxiang9.png',
          'description':
              'Technical deep diver exploring shipwrecks and underwater caves. Marine archaeology buff.',
        },
        {
          'username': 'sea',
          'name': 'Lyra',
          'email': 'lyra@example.com',
          'avatar': 'assets/images/touxiang10.png',
          'description':
              'Ocean conservationist focusing on plastic pollution. Organizing beach cleanups and diving tours.',
        },
      ];

      for (var user in sampleUsers) {
        await createUser(
          username: user['username']!,
          password: '123456',
          name: user['name']!,
          email: user['email']!,
          avatar: user['avatar']!,
          description: user['description']!,
        );
      }

      // Create some follow relationships
      // User 1 follows users 2, 3, 4
      final user1 = getUserByUsername('lalala');
      final user2 = getUserByUsername('ocean');
      final user3 = getUserByUsername('coral');
      final user4 = getUserByUsername('blue');

      if (user1 != null && user2 != null) {
        await followUser(user1.id, user2.id);
      }

      if (user1 != null && user3 != null) {
        await followUser(user1.id, user3.id);
      }

      if (user1 != null && user4 != null) {
        await followUser(user1.id, user4.id);
      }

      // User 2 follows users 1, 5
      final user5 = getUserByUsername('shark');

      if (user2 != null && user1 != null) {
        await followUser(user2.id, user1.id);
      }

      if (user2 != null && user5 != null) {
        await followUser(user2.id, user5.id);
      }
    }
  }
}
